using ClosedXML.Excel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PHMEE.Entities.DaqInfo.Ams;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Guids;

namespace PHMEE.ConsoleTools.Ams;

/// <summary>
/// 用于 Ams 开关量 Digital 在设备运维页面展示设备对应的开关量状态的 DigitalConfig 映射表的导入器
/// </summary>
public class DigitalConfigImporter
{
    public const string CommandName = "import-digital-config";
    
    private readonly ILogger<CommandLineService> _commandLineLogger;
    
    private IRepository<DigitalConfig, Guid> _digitalConfigRepository;
    private ILogger<DigitalConfigImporter> _logger;
    private IGuidGenerator _guidGenerator;

    public DigitalConfigImporter(ILogger<CommandLineService> commandLineLogger)
    {
        _commandLineLogger = commandLineLogger;
    }
    
    public async Task RunCommandAsync(string[] commandParts, IServiceProvider serviceProvider)
    {
        if (commandParts.Length != 3)
        {
            throw new UserFriendlyException("请提供船舶 Id 和 Excel 文件路径");
        }
        
        var vesselId = commandParts[1];
        var filePath = commandParts[2];
        
        var vesselIdGuid = Guid.TryParse(vesselId, out var id) ? id : throw new UserFriendlyException("vesselId 不是有效的 Guid");
        if (string.IsNullOrWhiteSpace(filePath))
        {
            throw new UserFriendlyException("Excel 文件路径不能为空");
        }
        
        _digitalConfigRepository = serviceProvider.GetRequiredService<IRepository<DigitalConfig, Guid>>();
        _logger = serviceProvider.GetRequiredService<ILogger<DigitalConfigImporter>>();
        _guidGenerator = serviceProvider.GetRequiredService<IGuidGenerator>();
        
        await ImportAsync(vesselIdGuid, filePath);
    }
    
    private async Task ImportAsync(Guid vesselId, string filePath)
    {
        await using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        using var workbook = new XLWorkbook(fileStream);
        
        var worksheet = workbook.Worksheet(1);
        
        var rows = worksheet.RangeUsed()?.RowsUsed().Skip(1) ?? throw new UserFriendlyException("Excel 文件中没有数据");

        List<DigitalConfig> digitalConfigs = [];
        
        foreach (var row in rows)
        {
            var tagName = row.Cell("A").GetValue<string>()?.Trim().ToLower() ?? throw new UserFriendlyException("TagName 不能为空");
            var unitIdString = row.Cell("B").GetValue<string>();
            if (!Guid.TryParse(unitIdString, out var unitId))
            {
                throw new UserFriendlyException("UnitId 不是有效的 Guid");
            }
            
            digitalConfigs.Add(new DigitalConfig(_guidGenerator.Create(), vesselId, tagName, unitId));
            _logger.LogInformation("构建 DigitalConfig: {tagName} - {unitId}", tagName, unitId);
        }
        
        await _digitalConfigRepository.InsertManyAsync(digitalConfigs);
        _logger.LogInformation("DigitalConfig 导入完成");
    }
}